<template>
  <!-- 搜索区域 -->
  <el-form :model="page" class="search-area">
    <el-row>
      <el-col :span="12">
        <el-form-item label="仓库编码" prop="warehouseCode">
          <el-input v-model="page.warehouseCode" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="page.warehouseName" />
        </el-form-item>
      </el-col>
    </el-row>
    <div class="operation-buttons">
      <el-button type="primary" @click="fetchData()">搜索</el-button>
      <el-button @click="clearForm()">清空</el-button>
    </div>
  </el-form>

  <!-- 操作按钮 -->
  <div class="action-buttons">
    <el-button type="primary" @click="openAddDialog">添加</el-button>
  </div>

  <!-- 数据表格 -->
  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="warehouseCode" label="仓库编码" width="120">
      <template #default="{ row }">
        <span style="color: #409eff; cursor: pointer">{{ row.warehouseCode }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="warehouseName" label="仓库名称" width="120" />
    <el-table-column prop="warehouseposition" label="位置" width="120" />
    <el-table-column prop="warehousearea" label="面积" width="120" />
    <el-table-column prop="warehousepeople" label="负责人" width="120" />
    <el-table-column label="是否冻结" width="120">
      <template #default="{ row }">
        <el-switch v-model="row.isFrozen" size="small" />
      </template>
    </el-table-column>
    <el-table-column prop="warehousenotes" label="备注" width="120" />
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-link type="primary" size="small" @click="openEditDialog(scope.row)">修改</el-link>
        <el-link type="primary" size="small" @click="handleDelete(scope.row.warehouseId)">删除</el-link>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加对话框 -->
  <el-dialog v-model="addDialogVisible" title="添加仓库设置" width="800">
    <el-form :model="addForm" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="仓库编码" prop="warehouseCode">
            <div style="display: flex; align-items: center; gap: 10px;">
              <el-input v-model="addForm.warehouseCode" placeholder="请输入仓库编码" />
              <el-switch v-model="addForm.autoGenerate" size="small" @change="handleAutoGenerate" label="自动生成" />
            </div>
          </el-form-item>
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-input v-model="addForm.warehouseName" />
          </el-form-item>
          <el-form-item label="负责人" prop="warehousepeople">
            <el-input v-model="addForm.warehousepeople" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="面积" prop="warehousearea">
            <div style="display: flex; align-items: center; gap: 5px;">
              <el-button type="text" @click="addForm.warehousearea--" size="small">-</el-button>
              <el-input v-model.number="addForm.warehousearea" style="width: 80px;" placeholder="0" />
              <el-button type="text" @click="addForm.warehousearea++" size="small">+</el-button>
            </div>
          </el-form-item>
          <el-form-item label="位置" prop="warehouseposition">
            <el-input v-model="addForm.warehouseposition" type="textarea" rows="2" />
          </el-form-item>
          <el-form-item label="备注" prop="warehousenotes">
            <el-input v-model="addForm.warehousenotes" type="textarea" rows="2" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改对话框 -->
  <el-dialog v-model="editDialogVisible" title="修改仓库" width="500">
    <el-form :model="editForm" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="仓库编码" prop="warehouseCode">
            <div style="display: flex; align-items: center; gap: 10px;">
              <el-input v-model="editForm.warehouseCode" placeholder="请输入仓库编码" />
              <el-switch v-model="editForm.autoGenerate" size="small" @change="handleAutoGenerate" label="自动生成" />
            </div>
          </el-form-item>
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-input v-model="editForm.warehouseName" />
          </el-form-item>
          <el-form-item label="负责人" prop="warehousepeople">
            <el-input v-model="editForm.warehousepeople" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="面积" prop="warehousearea">
            <div style="display: flex; align-items: center; gap: 5px;">
              <el-button type="text" @click="editForm.warehousearea--" size="small">-</el-button>
              <el-input v-model.number="editForm.warehousearea" style="width: 80px;" placeholder="0" />
              <el-button type="text" @click="editForm.warehousearea++" size="small">+</el-button>
            </div>
          </el-form-item>
          <el-form-item label="位置" prop="warehouseposition">
            <el-input v-model="editForm.warehouseposition" type="textarea" rows="2" />
          </el-form-item>
          <el-form-item label="备注" prop="warehousenotes">
            <el-input v-model="editForm.warehousenotes" type="textarea" rows="2" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">提交</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 分页组件 -->
  <el-pagination
    v-model:current-page="page.index"
    v-model:page-size="page.size"
    :page-sizes="[1, 5, 10, 15]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="page.totalCount"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    prev-text="上一页"
    next-text="下一页"
    class="mt-4"
  />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import type { ComponentSize } from 'element-plus';
const apiUrl = import.meta.env.VITE_APP_API_URL;
// 数据声明
const size = ref<ComponentSize>('default');
const background = ref(false);
const disabled = ref(false);

// 分页数据（修正驼峰命名，保持一致性）
const page = reactive({
  totalCount: 0,
  index: 1,
  size: 15,
  warehouseCode: '',
  warehouseName: ''
});

// 对话框状态
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);

// 添加表单数据（修正重复属性声明）
const addForm = reactive({
  warehouseCode: '',
  warehouseName: '',
  warehouseposition: '',
  warehousearea: 0,
  warehousepeople: '',
  isFrozen: true,
  warehousenotes: '',
  libraryId: 0,
  isDelete: true,
  autoGenerate: false 
});

// 修改表单数据（修正重复属性声明，添加类型声明）
const editForm = reactive({
  warehouseId: 0,
  warehouseCode: '',
  warehouseName: '',
  warehouseposition: '',
  warehousearea: 0,
  warehousepeople: '',
  isFrozen: true,
  warehousenotes: '',
  libraryId: 0,
  isDelete: true,
  autoGenerate: false 
});

// 表格数据（添加类型声明）
const tableData = ref<Array<any>>([]);

// 生命周期钩子
onMounted(() => {
  fetchData();
});

// 数据获取与处理（合并重复的API调用，优化页码处理）
const fetchData = () => {
  // 处理页码越界（先重置可能的错误页码）
  if (page.index < 1) page.index = 1;

  axios.get(apiUrl+'/T5/Setting/SettingShow/SettingShow',{ params: page })
    .then(res => {
      tableData.value = res.data.data || [];
      page.totalCount = res.data.totalCount || 0;

      // 二次检查页码越界（避免总页数为0时出错）
      const totalPages = page.totalCount > 0 ? Math.ceil(page.totalCount / page.size) : 1;
      if (page.index > totalPages) {
        page.index = totalPages;
        return fetchData(); // 递归获取正确页码数据
      }
    })
    .catch(error => {
      // console.error('获取数据失败:', error);
      // ElMessage.error('获取数据失败');
    });
};

// 分页控制（修正参数名，保持驼峰一致）
const handleSizeChange = (val: number) => {
  page.size = val;
  page.index = 1;
  ElMessage.info(`已切换为每页 ${val} 条数据`);
  fetchData();
};

const handleCurrentChange = (val: number) => {
  page.index = val;
  fetchData();
};

// 搜索操作
const clearForm = () => {
  page.warehouseCode = '';
  page.warehouseName = '';
  page.index = 1;
  fetchData();
};

// 添加操作（优化自动生成逻辑，避免重复代码）
const openAddDialog = () => {
  addDialogVisible.value = true;
  Object.assign(addForm, {
    warehouseCode: '',
    warehouseName: '',
    warehouseposition: '',
    warehousearea: 0,
    warehousepeople: '',
    isFrozen: true,
    warehousenotes: '',
    libraryId: 0,
    isDelete: true,
    autoGenerate: false 
  });
};

const submitAddForm = async () => {
  if (addForm.autoGenerate) {
    addForm.warehouseCode = generateWarehouseCode();
  }

  if (!addForm.warehouseCode.trim()) {
    ElMessage.error('仓库编码不能为空');
    return;
  }

  if (!addForm.warehouseName.trim()) {
    ElMessage.error('仓库名称为必填项');
    return;
  }

  try {
    const res = await axios.post(apiUrl+'/T6/setting/Addsetting', addForm);
    if (res.data.code === 100) {
      ElMessage.success('添加成功');
      addDialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error('添加失败');
    }
  } catch (error) {
    console.error('添加数据失败:', error);
    ElMessage.error('添加数据失败');
  }
};

// 修改操作
const openEditDialog = (row: any) => {
  editDialogVisible.value = true;
  Object.assign(editForm, row);
};

const submitEditForm = async () => {
  if (editForm.autoGenerate) {
    editForm.warehouseCode = generateWarehouseCode();
  }

  if (!editForm.warehouseName.trim()) {
    ElMessage.error('仓库名称为必填项');
    return;
  }

  try {
    const res = await axios.put(apiUrl+'/T6/setting/Updatesetting', editForm);
    if (res.data.code === 206) {
      ElMessage.success('修改成功');
      editDialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error('修改失败');
    }
  } catch (error) {
    console.error('修改数据失败:', error);
    ElMessage.error('修改数据失败');
  }
};

// 辅助功能（提取公共编码生成函数）
const generateWarehouseCode = () => {
  return new Date().toISOString().replace(/[-:.T]/g, '').substring(0, 14);
};

const handleAutoGenerate = (e: boolean) => {
  // 根据当前操作的表单类型生成编码（通过组件状态判断当前是添加还是修改对话框）
  if (addDialogVisible.value) {
    addForm.warehouseCode = e ? generateWarehouseCode() : '';
  } else if (editDialogVisible.value) {
    editForm.warehouseCode = e ? generateWarehouseCode() : '';
  }
};
const handleDelete = (warehouseId: number) => {
  if (!warehouseId) {
    ElMessage.error('仓库 ID 为空，无法删除');
    return;
  }

  const targetWarehouse = tableData.value.find(item => item.warehouseId === warehouseId);
  if (targetWarehouse) {
    targetWarehouse.isDelete = false;
    axios.put(apiUrl+'/T6/setting/Updatesetting', targetWarehouse)
      .then(res => {
        if (res.data.code === 206) {
          ElMessage.success('删除成功（逻辑删除）');
          fetchData();
        } else {
          ElMessage.error('删除失败');
        }
      })
      .catch(error => {
        console.error('删除数据失败:', error);
        ElMessage.error('删除数据失败');
      });
  }
};
</script>

<style scoped>
/* 公共样式 */
.el-table__header th {
  background-color: #f5f7fa;
  color: #606266;
}

.el-table__row--hover {
  background-color: #f5f7fa !important;
}

/* 布局样式 */
.search-area {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.action-buttons {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px;
}

/* 分页组件样式 */
.mt-4 {
  margin-top: 20px;
}
</style>